import { useState } from "react";
import { message } from "antd";
import { useModel } from "umi";

export default function uploadFilesModal() {
    const { gatewayUrl } = useModel("organization.info");

    const [annexFiles, setAnnexFiles] = useState([]);
    const [previewShow, setPreviewShow] = useState(false);
    const [previewImage, setPreviewImage] = useState(false);
    const [maxFiles, setMaxFiles] = useState(5);
    const [deletedFiles, setDeletedFiles] = useState([]);

    const beforeUpload = (file, fileList) => {
        const { uid, name, path, size, type } = file;
        const photo = annexFiles.find((item) => item.path === file.path);
        if (!photo) {
            let newList = annexFiles.slice(); // JSON.parse(JSON.stringify(annexFiles));
            let data = { uid, name, path, size, type, url: file.path, isNew: true };
            newList.push(data);
            setAnnexFiles(newList);
        } else message.warning("不能上传重复的图片，请重新选择图片");
        return false;
    };

    const fileRemove = (file) => {
        let newData = annexFiles.filter((item) => item.path !== file.path);
        setAnnexFiles(newData);
        if (file.isNew === false) {
            let i = deletedFiles.findIndex((item) => item.path === file.path);
            i === -1 && setDeletedFiles(deletedFiles.concat([file]));
        }
        return false;
    };

    //查看大图
    const filePreview = (file) => {
        setPreviewImage(file.previewUrl || file.path);
        setPreviewShow(true);
    };

    const closePreview = () => {
        setPreviewShow(false);
    };

    const setEditAnnexFiles = (files) => {
        setAnnexFiles(
            files.map((item) => {
                let url, previewUrl;
                if (item.isNew === undefined) item.isNew = false;
                if (item.isNew === true) {
                    url = item.path;
                } else {
                    url = gatewayUrl + "/file/download?width=60&type=image&filepath=" + item.path;
                    previewUrl = gatewayUrl + "/file/download?filepath=" + item.path;
                }

                return { ...item, url, previewUrl };
            })
        );
    };

    const addDeleteFile = (file) => {
        let i = deletedFiles.findIndex((item) => item.path === file.path);
        i === -1 && setDeletedFiles(deletedFiles.concat([file]));
    };

    return {
        annexFiles,
        setAnnexFiles,
        setEditAnnexFiles,
        fileRemove,
        filePreview,
        closePreview,
        previewShow,
        setPreviewShow,
        previewImage,
        setPreviewImage,
        beforeUpload,
        maxFiles,
        setMaxFiles,
        deletedFiles,
        setDeletedFiles,
        addDeleteFile,
    };
}
